package cs.xwi7xwa.activities;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import com.bumptech.bumpapi.BumpAPIListener;
import com.bumptech.bumpapi.BumpDisconnectReason;
import com.google.code.microlog4android.config.PropertyConfigurator;

import cs.xwi7xwa.R;
import cs.xwi7xwa.data.BumpResources;
import cs.xwi7xwa.data.ExhibitDbAdapter;
import cs.xwi7xwa.data.FactDbAdapter;
import cs.xwi7xwa.templates.BumpListTemplate;
import cs.xwi7xwa.templates.Xwi7xwaToast;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class BumpTradeView extends BumpListTemplate implements BumpAPIListener {

    private Handler handler = new Handler();
    private FactDbAdapter dbAdapter;
    private Cursor cursor;
    private ArrayList<Integer> hiddenFacts = new ArrayList<Integer>();
    private int incomingFact = -1;
    private Dialog waitingDialog = null;
    private int outgoingFact = -1;
    private boolean receivedOk = false;
    private boolean sentOk = false;
    private Timer myTimer;

    private final String TRADE_OK_STR = "trade ok";
    private final String TRADE_CANCEL_STR = "trade cancel";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.trade_bump);
        BumpResources.BUMP_CONNECTION.setListener(this, handler);

        dbAdapter = new FactDbAdapter(this);
        try {
            dbAdapter.open();
        } catch (IOException e) {
            e.printStackTrace();
        }

        sendMyFacts();

        // Config logger
        PropertyConfigurator.getConfigurator(this).configure();

        // Log this method's execution
        log(null);
    }

    private void sendMyFacts() {
        cursor = dbAdapter.fetchVisibleFactExhibit();
        startManagingCursor(cursor);

        String myFacts = new String();
        if (cursor.moveToFirst()) {
            myFacts = Integer.toString(cursor
                .getInt(FactDbAdapter.KEY_ID_COLUMN));

            while (cursor.moveToNext()) {
                myFacts = myFacts + ","
                        + Integer.toString(cursor
                            .getInt(FactDbAdapter.KEY_ID_COLUMN));
            }
        }

        try {
            BumpResources.BUMP_CONNECTION.send(myFacts.getBytes("UTF-8"));
        } catch (Exception e) {}
    }

    private void refreshList() {      
        cursor = dbAdapter.fetchCollectedFacts(hiddenFacts);
        startManagingCursor(cursor);
        
        
        if (cursor == null) {            
            View layout = getLayoutInflater().inflate(R.layout.toast,
                (ViewGroup) findViewById(R.id.toastText));
            Xwi7xwaToast noTradeToast = new Xwi7xwaToast(layout,
                getApplicationContext(), "No tradeable facts!");
            noTradeToast.show();
        } else {
            String[] displayCol = new String[] { ExhibitDbAdapter.KEY_NAME,
                    FactDbAdapter.KEY_DESC, FactDbAdapter.KEY_NUMBER };

            int[] toView = new int[] { R.id.tradeItemFirstLine,
                    R.id.tradeItemSecondLine, R.id.tradeItemNumber };

            setListAdapter(new SimpleCursorAdapter(this,
                R.layout.trade_list_item, cursor, displayCol, toView));
        }
    }

    public void bumpDataReceived(byte[] chunk) {
        try {
            String data = new String(chunk, "UTF-8");
            // Toast.makeText(this, data, 0).show();
            if (data.contains(",")) {
                while (data.length() != 0) {
                    int ii = 1;
                    while (ii < data.length() && data.charAt(ii) != ',') {
                        ii++;
                    }

                    Integer factId = Integer.parseInt(data.substring(0, ii));
                    hiddenFacts.add(factId);

                    data = data.substring(Math.min(ii + 1, data.length()), data
                        .length());
                }

                refreshList();
            } else if (data.equals(TRADE_OK_STR)) {
                receivedOk = true;

                if (sentOk) {
                    receiveFact();
                }
            } else if (data.equals(TRADE_CANCEL_STR)) {
                // TODO
            } else {
                incomingFact = Integer.parseInt(data);

                if (outgoingFact != -1) {
                    trade();
                }
            }
        } catch (Exception e) {}
    }

    public void bumpDisconnect(BumpDisconnectReason reason) {
        View layout = getLayoutInflater().inflate(R.layout.toast,
            (ViewGroup) findViewById(R.id.toastText));
        Xwi7xwaToast disconnectedToast = new Xwi7xwaToast(layout,
            getApplicationContext(), "Disconnected: " + reason.name());
        disconnectedToast.show();

        log(null);

        dbAdapter.close();

        Intent intent = new Intent(getApplicationContext(), MyFactsView.class);
        startActivityForResult(intent, 0);
    }

    @Override
    protected void onListItemClick(ListView listView, View view, int position,
            long id) {

        super.onListItemClick(listView, view, position, id);
        final int outgoingId = (int) id;

        Cursor cursor = dbAdapter.fetch((int) id);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(cursor.getString(cursor
            .getColumnIndex(FactDbAdapter.KEY_DESC)));
        builder.setTitle("Trade fact?");
        builder.setCancelable(false);
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            int dialogId = (int) outgoingId;

            public void onClick(DialogInterface dialog, int id) {
                outgoingFact = dialogId;

                try {
                    BumpResources.BUMP_CONNECTION.send(Long.toString(
                        outgoingFact).getBytes("UTF-8"));
                } catch (Exception e) {}

                if (incomingFact != -1) {
                    trade();
                } else {
                    waitingDialog = ProgressDialog.show(BumpTradeView.this, "",
                        "Waiting for incoming fact ...", true);
                }
            }
        });
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();

                BumpTradeView.this.log(new String[] { "Selected wrong fact." });
            }
        });
        AlertDialog tradeDialog = builder.create();
        tradeDialog.show();
    }

    private void trade() {
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }

        LayoutInflater inflater = (LayoutInflater) this
            .getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.trade_bump_dialog,
            (ViewGroup) findViewById(R.id.layout_root));

        ExhibitDbAdapter exhibitDbAdapter = new ExhibitDbAdapter(this);
        try {
            exhibitDbAdapter.open();
        } catch (IOException e) {}

        Cursor cursor = dbAdapter.fetch(outgoingFact);
        startManagingCursor(cursor);

        int exhibitId = cursor.getInt(FactDbAdapter.KEY_EXHIBITID_COLUMN);
        ((TextView) layout.findViewById(R.id.topFactSecondText)).setText(cursor
            .getString(FactDbAdapter.KEY_DESC_COLUMN));
        cursor.close();

        Cursor exhibitCursor = exhibitDbAdapter.fetch(exhibitId);
        String exhibitName = exhibitCursor.getString(exhibitCursor
            .getColumnIndex(ExhibitDbAdapter.KEY_NAME));
        exhibitCursor.close();

        ((TextView) layout.findViewById(R.id.topFactFirstText))
            .setText(exhibitName);

        cursor = dbAdapter.fetch(incomingFact);
        startManagingCursor(cursor);

        exhibitId = cursor.getInt(FactDbAdapter.KEY_EXHIBITID_COLUMN);
        ((TextView) layout.findViewById(R.id.bottomFactSecondText))
            .setText(cursor.getString(FactDbAdapter.KEY_DESC_COLUMN));
        cursor.close();

        exhibitCursor = exhibitDbAdapter.fetch(exhibitId);
        exhibitName = exhibitCursor.getString(exhibitCursor
            .getColumnIndex(ExhibitDbAdapter.KEY_NAME));
        exhibitCursor.close();

        ((TextView) layout.findViewById(R.id.bottomFactFirstText))
            .setText(exhibitName);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(layout);

        builder.setPositiveButton("Confirm", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    sentOk = true;

                    BumpResources.BUMP_CONNECTION.send(TRADE_OK_STR
                        .getBytes("UTF-8"));

                    log(new String[] { "Confirmed trade." });

                    if (receivedOk) {
                        receiveFact();
                    } else {
                        if (waitingDialog != null) {
                            waitingDialog.dismiss();
                            waitingDialog = null;
                        }
                        waitingDialog = ProgressDialog.show(BumpTradeView.this,
                            "", "Waiting for confirmation ...", true);
                        
//                        myTimer = new Timer();
//                        myTimer.schedule(new TimerTask() {
//                            public void run() {
//                               receiveFact();
//                            }                            
//                        }, 8000);
                        
                        handler = new Handler();
                        Runnable runnable = new Runnable() {
                            public void run() {
                                BumpTradeView.this.receiveFact();
                            }
                        };
                        handler.postDelayed(runnable, 5000);
                    }

                    BumpResources.BUMP_CONNECTION.send(TRADE_OK_STR
                        .getBytes("UTF-8"));
                } catch (UnsupportedEncodingException e) {}
            }
        });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    public void receiveFact() {
        if (sentOk == true && outgoingFact != -1 && incomingFact != -1) {
            if (waitingDialog != null) {
                waitingDialog.dismiss();
                waitingDialog = null;
            }

            View layout = getLayoutInflater().inflate(R.layout.toast,
                (ViewGroup) findViewById(R.id.toastText));
            Xwi7xwaToast newFactToast = new Xwi7xwaToast(layout,
                getApplicationContext(), "Received new fact!");
            newFactToast.show();

            dbAdapter.setHidden(incomingFact, false);
            sendMyFacts();

            log(new String[] {"Received new fact! Traded fact " + 
                    outgoingFact + ", received fact " + incomingFact});

            receivedOk = false;
            sentOk = false;
            outgoingFact = -1;
            incomingFact = -1;
        }
    }

    @Override
    public void onStop() {
        if (BumpResources.BUMP_CONNECTION != null) {
            BumpResources.BUMP_CONNECTION.disconnect();
            BumpResources.BUMP_CONNECTION = null;
        }

        super.onStop();
    }

    public void disconnectTrade(View view) {
        if (BumpResources.BUMP_CONNECTION != null) {
            BumpResources.BUMP_CONNECTION.disconnect();
            BumpResources.BUMP_CONNECTION = null;
        }
    }
}
